package LeetCode.Medium;


import java.util.HashMap;
import java.util.Map;

/*
重建二叉树，根据中序和前序遍历
 */
public class Question003 {
}

class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int x){
        val = x;
    }
}

class Solution{
    private Map<Integer,Integer> indexMap;

    public TreeNode myBuildTree(int[] preorder, int[] inorder, int preorder_left, int preorder_right,int inorder_left, int inorder_right){
        if(preorder_left > preorder_right){
            return null;
        }
        int preorder_root = preorder_left;
        int inorder_root = indexMap.get(preorder[preorder_root]);
        TreeNode root = new TreeNode(preorder[preorder_root]);
        int size_left_subtree = inorder_root - inorder_left;
        root.left = myBuildTree(preorder,inorder,preorder_left+1,preorder_left+size_left_subtree, inorder_left,inorder_root-1);
        root.left = myBuildTree(preorder,inorder,preorder_left+size_left_subtree,preorder_right, inorder_root+1,inorder_right);
        return root;
    }

    public TreeNode buildTree(int[] preorder, int[] inorder){
        int n = preorder.length;
        indexMap = new HashMap<>();
        for (int i = 0; i < n; i++) {
            indexMap.put(inorder[i],i);
        }
        return myBuildTree(preorder, inorder,0,n-1,0,n-1);
    }
}
